<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * oauth 认证客户端
 * 需要注意的是 $apply_user_id 指的是申请 key 的用户的 id
 * 而 $consumer_user_id 指的才是授权用户的 id
 *
 * @author <judasnow@gmail.com>
 */
class oauth_client{
	private $_CI;
	private $_server_base_uri;
	private $store;

	public function __construct(){
		 $this->_CI =& get_instance();
		 require_once( APPPATH . "libraries/oauth/OAuthStore.php" );
		 require_once( APPPATH . 'libraries/oauth/OAuthServer.php' );
		 require_once( APPPATH . 'libraries/oauth/OAuthRequester.php' );
		 $this->_CI->config->load( 'oauth' );
		 $db_options = array(
			 'server' => $this->_CI->config->item( 'db_server' ),	 
			 'username' => $this->_CI->config->item( 'db_username' ),
			 'password' => $this->_CI->config->item( 'db_password' ),
			 'database' => $this->_CI->config->item( 'db_name' )
		 );
		 $this->store = OAuthStore::instance( 'MySQL' , $db_options );

		 $this->consumer_key = $this->_CI->config->item( 'key' );
		 $this->consumer_secret = $this->_CI->config->item( 'secret' );
		 $this->apply_user_id = $this->_CI->config->item( 'apply_user_id' );
		 $this->_server_base_uri = $this->_CI->config->item( 'server_base_uri' );
	}

	//默认操作为请求未授权的 token 
	public function index(){
	/*{{{*/
		 $this->request_token();
	}/*}}}*/

	//获取未授权的 token
	public function request_token(){
	/*{{{*/
		try{
			$token = OAuthRequester::requestRequestToken( $this->consumer_key , $this->apply_user_id );
			//获取成功之后跳转到服务提供方的认证页面
			header( "Location: {$this->_server_base_uri}oauth/authorize?consumer_key={$this->consumer_key}&&oauth_token={$token['token']}&&apply_user_id={$this->apply_user_id}" );
			exit;
		}catch( Exception $e ){
			echo $e->getMessage();
		}
	}/*}}}*/

	//添加一条服务提供方信息到数据库中
	public function add_server(){
	/*{{{*/
		 $server = array(
			 'consumer_key'      => $this->consumer_key,
			 'consumer_secret'   => $this->consumer_secret,
			 'server_uri'        => $this->_server_base_uri,
			 'signature_methods' => array( 'HMAC-SHA1', 'PLAINTEXT' ),
			 'request_token_uri' => $this->_server_base_uri . 'oauth/request_token',
			 'authorize_uri'     => $this->_server_base_uri . 'oauth/authorize',
			 'access_token_uri'  => $this->_server_base_uri . 'oauth/access_token'
		 );
		 try{
			 $consumer_key = $this->store->updateServer( $server , $this->apply_user_id );
			 echo "add server ok";
		 }catch( Exception $e ){	 
			 //echo "尝试添加一条服务提供方信息到数据库中时失败";
			 echo $e->getMessage();
		 }
	}/*}}}*/

	/**
	 * 回调页面
	 * 请求一个 access_token
	 */
	public function callback(){
	/*{{{*/
		 $consumer_key = $_GET['consumer_key'];
 		 $oauth_token = $_GET['oauth_token'];
		 $consumer_user_id = $_GET['consumer_user_id'];
		 $apply_user_id = $_GET['apply_user_id'];
		 try{
			 OAuthRequester::requestAccessToken( $consumer_key , $oauth_token , $apply_user_id );
			 //成功获取 access token 
			 //跳转到登录页面		 
			 //保存 apply_user_id , 以及consumer_user_id 
			 $this->_CI->session->set_userdata( 'user' , array( 'consumer_user_id'=>$consumer_user_id , 'apply_user_id'=>$apply_user_id ) );
			 header( 'Location: /auth/do_login' );
			 exit;
		 }catch( OAuthException $e ){
			 echo $e->getMessage();
		 }
	}/*}}}*/

	/**
	 * @param $uri 需要请求的 $uri 
	 * @param $only_return_body bool 仅仅返回 body 部分
	 */
	public function request( $uri , $only_return_body = TRUE ){
	/*{{{*/
		 $params = array(
			 'method' => 'GET'
		 );
		 //todo 需要测试 uri 是否有效
		 try{
			 $req = new OAuthRequester( $uri, 'GET', $params );
			 $result = $req->doRequest( $this->apply_user_id );
			 if( $only_return_body ){
				 return $result['body'];	 
			 }else{
				 return $result;
			 }
		 }catch( Exception $e ){
			 echo $e->getMessage();
			 //获取 api 信息错误 
			 die( '{"res":"error"}' );
		 }
	}/*}}}*/

	 public function list_consumer_tokens( $user_id ){
	 /*{{{*/
		 return $this->store->getServerToken( $user_id );
	 }/*}}}*/
	
	/**
	 * 删除一个 server 的信息
	 * @todo 山寨的
	 */
	public function do_del_app( $server_base_uri ){
	/*{{{*/
	 	 echo 'Del=' . $server_base_uri;
	 }/*}}}*/
}
